﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace TheOliver.Controls
{
    public class ExecuteCommandAction : TriggerAction<FrameworkElement>
    {

        [Category("ExecuteCommandAction Properties"),
        Description("The Command that will be executed by this TriggerAction")]
        public string TargetCommand
        {
            get { return (string)GetValue(TargetCommandProperty); }
            set { SetValue(TargetCommandProperty, value); }
        }

        public static readonly DependencyProperty TargetCommandProperty =
            DependencyProperty.Register("Target Command",
                                        typeof(string),
                                        typeof(ExecuteCommandAction),
                                        new PropertyMetadata
                                            (TargetCommandChanged));

        private static void TargetCommandChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {

        }

        protected override void Invoke(object parameter)
        {
            var path = TargetCommand;
            var dc = AssociatedObject.DataContext;
            var targetCommand = 
                dc.GetType().GetProperty(path).GetValue(dc, null) as ICommand;

            if (targetCommand != null && targetCommand.CanExecute(parameter))
            {
                targetCommand.Execute(parameter);
            }
        }
    }
}
